import torch
from torch import nn


class Pointnet(nn.Module):
    def __init__(self, encoder_channel):
        super().__init__()
        self.encoder_channel = encoder_channel
        self.first_conv = nn.Sequential(
            nn.Conv1d(3, 128, 1),
            nn.BatchNorm1d(128),
            nn.ReLU(inplace=True),
            nn.Conv1d(128, 256, 1)
        )
        self.second_conv = nn.Sequential(
            nn.Conv1d(512, 512, 1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),
            nn.Conv1d(512, self.encoder_channel, 1)
        )

    def forward(self, point_groups):
        '''
            point_groups : B G N 3
            -----------------
            feature_global : B G C
        '''
        bs, g, n, _ = point_groups.shape
        point_groups = point_groups.reshape(bs * g, n, 3)
        # encoder
        feature = self.first_conv(point_groups.transpose(2, 1))
        feature_global = torch.max(feature, dim=2, keepdim=True)[0]
        feature = torch.cat([feature_global.expand(-1, -1, n), feature], dim=1)
        feature = self.second_conv(feature)
        feature_global = torch.max(feature, dim=2, keepdim=False)[0]
        return feature_global.reshape(bs, g, self.encoder_channel)



if __name__ == '__main__':
    # 模拟点云数据
    batch_size = 4  # 批次大小
    groups = 2  # 点云组数
    points_per_group = 100  # 每组点数
    point_dims = 7  # 点的维度

    # 实例化模型
    encoder_channel = 1024  # 设定编码器的输出通道数
    model = Pointnet(input_dim=point_dims, encoder_channel=encoder_channel)

    # 创建一个随机点云数据张量
    point_groups = torch.randn(batch_size, groups, points_per_group, point_dims)

    # 通过模型进行前向传播
    output = model(point_groups)

    # 输出结果的形状 torch.Size([4, 2, 1024])
    print(output.shape)
